package com.mayikt.service;

import com.mayikt.entity.UserEntity;
import com.mayikt.manage.LoginManage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @ClassName LoginService
 * @Author 蚂蚁课堂余胜军 QQ644064779 www.mayikt.com
 * @Version V1.0
 **/
@RestController
@Slf4j
public class LoginService {
    @Autowired
    private LoginManage loginManage;

    /**
     * 登陆请求
     *
     * @param userEntity
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/login")
    public ResponseEntity<String> login(UserEntity userEntity) throws ExecutionException, InterruptedException {
        // 查询数据库
        UserEntity dbUser = dbLogin(userEntity);
        if (dbUser == null) {
            return ResponseEntity.status(500).body("账号或者是密码错误");
        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                loginLog(userEntity);
//                sendSms(userEntity);
//                sendEmail(userEntity);
//            }
//        }).start();
        Future<String> stringFuture = loginManage.asynLogin(userEntity);
        return ResponseEntity.status(200).body(stringFuture.get());
    }

    //com.mayikt.manage
    @Async
    public void asynLogin(UserEntity userEntity) {
        loginLog(userEntity);
        sendSms(userEntity);
        sendEmail(userEntity);
    }

    private UserEntity dbLogin(UserEntity userEntity) {
        log.info(">>>1.正在查询数据库登陆<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
        return new UserEntity();
    }

    private void loginLog(UserEntity userEntity) {
        log.info(">>>2.异步开始写登陆的日志<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
//        int i = 1 / 0;
    }

    private void sendSms(UserEntity userEntity) {
        log.info(">>>3.异步开始发送短信<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
    }

    private void sendEmail(UserEntity userEntity) {
        log.info(">>>4.异步开始发送邮件<<<");
        try {
            Thread.sleep(2000);
        } catch (Exception e) {

        }
    }
}
